<template>
  <el-tabs v-model="activeTab" class="query-tabs" @tab-change="tabChange">
    <el-tab-pane label="项目统计" name="0">
      <el-form :model="projectParams" ref="projectRef" :inline="true" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="省" prop="provinceId">
              <el-select v-model="projectParams.provinceId" placeholder="请选择省" @change="chooseProvince" clearable>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市" prop="cityId">
              <el-select v-model="projectParams.cityId" placeholder="请选择市" @change="chooseCity" clearable>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区/县" prop="countyId">
              <el-select v-model="projectParams.countyId" placeholder="请选择区/县" clearable>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="时间" prop="startTime">
            <el-space>
              <el-date-picker v-model="projectParams.startTime" type="year" value-format="YYYY"
                :disabled-date="disabledDateStart" />
              <span>至</span>
              <el-date-picker v-model="projectParams.entTime" type="year" value-format="YYYY"
                :disabled-date="disabledDate" />
            </el-space>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="getProjectList">查询</el-button>
            <el-button plain @click="resetproject">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-divider></el-divider>
      <el-scrollbar ref="scrollProjectRef" :height="echartHeight">
        <div id="projectEchartBar" style="width: 100%;height: 400px"></div>
        <div id="projectEchartLine" style="width: 100%;height: 400px"></div>
      </el-scrollbar>
    </el-tab-pane>
    <el-tab-pane label="数据统计" name="1">
      <el-form :model="analysisParams" ref="analysisRef" :inline="true" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="省" prop="provinceId">
              <el-select v-model="analysisParams.provinceId" placeholder="请选择省" @change="chooseAnalysisProvince"
                clearable>
                <el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="市" prop="cityId">
              <el-select v-model="analysisParams.cityId" placeholder="请选择市" @change="chooseAnalysisCity" clearable>
                <el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="区/县" prop="countyId">
              <el-select v-model="analysisParams.countyId" placeholder="请选择区/县" @change="chooseAnalysisCounty" clearable>
                <el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-form-item label="时间" prop="startTime">
            <el-space>
              <el-date-picker v-model="analysisParams.startTime" type="year" value-format="YYYY"
                :disabled-date="disabledAnalysisStart" />
              <span>至</span>
              <el-date-picker v-model="analysisParams.entTime" type="year" value-format="YYYY"
                :disabled-date="disabledAnalysis" />
            </el-space>
          </el-form-item>
          <el-form-item label="数据类型" prop="tableName">
            <el-space>
              <el-select v-model="analysisParams.dataType" @change="changeType" clearable>
                <el-option v-for="item in spaceTypeOption" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.dictItemCode"></el-option>
              </el-select>
              <el-select v-model="analysisParams.tableName" placeholder="请选择" clearable>
                <el-option v-for="item in codeTypeOption" :key="item.dictItemId" :label="item.dictItemName"
                  :value="item.description"></el-option>
              </el-select>
            </el-space>
          </el-form-item>
          <el-form-item label=" ">
            <el-button type="primary" @click="getAnalysisList">查询</el-button>
            <el-button plain @click="resetAnalysis">重置</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-divider></el-divider>
      <el-scrollbar ref="scrollDataRef" :height="echartHeight">
        <div id="dataEchartBar" style="width: 100%;height: 400px"></div>
        <div id="dataEchartLine" style="width: 100%;height: 400px"></div>
      </el-scrollbar>
    </el-tab-pane>
  </el-tabs>
</template>
<script setup>
import { getProvince, getChildArea } from "@/api/system/division"
import { getDict } from '@/api/system/dict'
import { useNow, useDateFormat } from '@vueuse/core'
import { getProject, getDate } from '@/api/achievementSearch/statisticAnalysis'
import * as echarts from 'echarts'

const { proxy } = getCurrentInstance()
const activeTab = ref('0')
const tabChange = (val) => {
  cityData.value = []
  areaData.value = []
  if (val == '1') {
    getSpaceType()
  }
}
const echartHeight = ref()

const provinceData = ref([])
const cityData = ref([])
const areaData = ref([])
const getProvinceData = () => {
  getProvince().then(res => {
    if (res.code == 200) {
      provinceData.value = res.data
    }
  })
}
const chooseProvince = (value) => {
  projectParams.value.cityId = null
  projectParams.value.countyId = null
  cityData.value = []
  areaData.value = []
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
}
const chooseCity = (value) => {
  projectParams.value.countyId = null
  areaData.value = []
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
}
const disabledDateStart = time => {
  return time.getTime() > new Date(projectParams.value.entTime)
}
const disabledDate = time => {
  return time.getTime() < new Date(projectParams.value.startTime)
}

const projectParams = ref({
  startTime: '2023',
  entTime: useDateFormat(useNow(), 'YYYY').value
})

const getProjectList = () => {
  getProject(projectParams.value).then(res => {
    renderBar('projectEchartBar', res.data)
    renderLine('projectEchartLine', res.data)
    nextTick(() => {
      console.log(proxy.$refs.scrollProjectRef.$el.clientHeight)
      echartHeight.value = proxy.$refs.scrollProjectRef.$el.clientHeight - proxy.$refs.projectRef.$el.clientHeight - 49
    })
  })
}

const resetprojectParams = () => {
  proxy.resetForm('projectRef')
  projectParams.value.entTime = useDateFormat(useNow(), 'YYYY').value
}
const resetproject = () => {
  resetprojectParams()
  getProjectList()
}
const chooseAnalysisProvince = (value) => {
  analysisParams.value.cityId = null
  analysisParams.value.countyId = null
  analysisParams.value.city = null
  analysisParams.value.county = null
  cityData.value = []
  areaData.value = []
  analysisParams.value.province = provinceData.value.find(item => item.id == value)?.name
  getChildArea(value).then(response => {
    cityData.value = response.data
  })
}
const chooseAnalysisCity = (value) => {
  analysisParams.value.countyId = null
  analysisParams.value.county = null
  areaData.value = []
  analysisParams.value.city = cityData.value.find(item => item.id == value)?.name
  getChildArea(value).then(response => {
    areaData.value = response.data
  })
}
const chooseAnalysisCounty = (value) => {
  analysisParams.value.county = areaData.value.find(item => item.id == value)?.name
}
const disabledAnalysisStart = time => {
  return time.getTime() > new Date(analysisParams.value.entTime)
}
const disabledAnalysis = time => {
  return time.getTime() < new Date(analysisParams.value.startTime)
}
const analysisParams = ref({
  startTime: '2023',
  entTime: useDateFormat(useNow(), 'YYYY').value
})
const spaceTypeOption = ref([])
const codeTypeOption = ref([])
const getSpaceType = () => {
  getDict('Space').then(res => {
    spaceTypeOption.value = res.data
  })
}
const changeType = (val) => {
  codeTypeOption.value = []
  analysisParams.value.tableName = ''
  getDict(val).then(res => {
    codeTypeOption.value = res.data
  })
}
const getAnalysisList = () => {
  if (!analysisParams.value.tableName) {
    proxy.$modal.msgWarning('请选择数据类型！')
    return
  }
  getDate(analysisParams.value).then(res => {
    renderBar('dataEchartBar', res.data)
    renderLine('dataEchartLine', res.data)
    nextTick(() => {
      echartHeight.value = proxy.$refs.scrollDataRef.$el.clientHeight - proxy.$refs.analysisRef.$el.clientHeight - 49
    })
  })
}
const resetAnalysisParams = () => {
  proxy.resetForm('analysisRef')
  analysisParams.value.entTime = useDateFormat(useNow(), 'YYYY').value
  analysisParams.value.status = null
}
const resetAnalysis = () => {
  resetAnalysisParams()
  getAnalysisList()
}

const renderBar = (id, data) => {
  let chartDom = document.getElementById(id)
  echarts.init(chartDom).dispose()
  let myChart = echarts.init(chartDom)
  let option = {
    xAxis: {
      type: 'category',
      name: '年份',
      data: data.map(item => item.year + '年')
    },
    yAxis: {
      type: 'value',
      name: '数量/个',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: {
        show: true,
        lineStyle: { type: 'dashed' }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: function (params) {
        let item = params[0]
        return `<p style='text-align: center'>${item.name}</p>${item.marker}数量：${item.value}`
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {
          type: 'png',
          name: '统计结果-柱状图',
        }
      },
      right: 100
    },
    series: [
      {
        data: data.map(item => item.count),
        type: 'bar',
        itemStyle: {
          color: '#107ce5'
        },
        barWidth: 40
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        realtime: true,
        show: data.length > 21,
        start: 0,
        end: data.length > 21 ? 40 : 100,
        height: 4,
        fillerColor: "rgba(17, 100, 210, 0.42)",
        borderColor: "rgba(17, 100, 210, 0.12)",
        handleSize: 20,
        showDetail: false,
        top: '96%'
      },
      {
        type: "inside",
        start: 0,
        end: 40,
        zoomOnMouseWheel: false,
        moveOnMouseWheel: true
      }
    ]
  }
  option && myChart.setOption(option)
}
const renderLine = (id, data) => {
  let chartDom = document.getElementById(id)
  echarts.init(chartDom).dispose()
  let myChart = echarts.init(chartDom)
  let option = {
    xAxis: {
      type: 'category',
      name: '年份',
      data: data.map(item => item.year + '年')
    },
    yAxis: {
      type: 'value',
      name: '数量/个',
      axisLine: { show: false },
      axisTick: { show: false },
      splitLine: {
        show: true,
        lineStyle: { type: 'dashed' }
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: function (params) {
        let item = params[0]
        return `<p style='text-align: center'>${item.name}</p>${item.marker}数量：${item.value}`
      }
    },
    toolbox: {
      feature: {
        saveAsImage: {
          type: 'png',
          name: '统计结果-折线图',
        }
      },
      right: 100
    },
    series: [
      {
        data: data.map(item => item.count),
        type: 'line',
        itemStyle: {
          color: '#107ce5'
        },
        symbolSize: 7,
        symbol: 'circle',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(129,183,255, 0.8)', }, 
            { offset: 1, color: 'rgba(129,183,255, 0.3)', }
          ]),
          // color: 'rgba(16,124,229, .3)'
        }
      }
    ]
  }
  option && myChart.setOption(option)
}

defineExpose({
  activeTab,
  getProvinceData,
  resetprojectParams,
  resetAnalysisParams
})
</script>
<style lang="scss" scoped>
.el-tabs {
  height: 100%;

  &>:deep(.el-tabs__content) {
    height: calc(100% - 55px);
  }
}
</style>